package top.txl.controller;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.txl.Dto.SetmealDto;
import top.txl.entity.PageBean;
import top.txl.entity.R;
import top.txl.entity.SetMeal;
import top.txl.exception.CustomerException;
import top.txl.service.SetmealService;
import top.txl.utils.JwtUtils;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/setmeal")
public class SetMealController {

    @Autowired
    private SetmealService setmealService;

    @PostMapping("/add")
    public R<String> add(HttpServletRequest request, @RequestBody SetmealDto setmealDto){

        String jwt = request.getHeader("Authorization");
        Claims claims = JwtUtils.parseJwt(jwt);
        Integer id = (Integer) claims.get("id");
        setmealDto.setCreateTime(LocalDateTime.now());
        setmealDto.setUpdateTime(LocalDateTime.now());
        setmealDto.setCreateUser(id);
        setmealDto.setUpdateUser(id);
        setmealDto.setStatus(1);
        setmealDto.setIsDeleted(0);

        int i = (int) ((Math.random() * 1000000000L));
        log.info("code,{}", i);
        setmealDto.setCode(i + "");

        setmealService.save(setmealDto);
        return R.success("新增成功");
    }

    @GetMapping("/lists")
    public R<PageBean> lists(@RequestParam (defaultValue = "1") Integer page,
                                     @RequestParam (defaultValue = "5") Integer pageSize,
                                     String keyWords){
        PageBean bean = setmealService.lists(page,pageSize,keyWords);
        return R.success(bean);
    }


    @GetMapping("/detail/{id}")
    public R<SetMeal> getDetail(@PathVariable Integer id){
        log.info("过去套餐详情,{}",id);
        SetMeal setMeal = setmealService.detail(id);
        return R.success(setMeal);
    }


    @GetMapping("/front/sLists/{categoryId}")
    public R<List<SetmealDto>> frontSetMeal(@PathVariable Integer categoryId){
        List<SetmealDto> lists = setmealService.frontLists(categoryId);
        return R.success(lists);
    }

    @PutMapping("/edit")
    public R<String> update(HttpServletRequest request, @RequestBody SetmealDto setmealDto){

        String jwt = request.getHeader("Authorization");
        Claims claims = JwtUtils.parseJwt(jwt);
        Integer id = (Integer) claims.get("id");

        setmealDto.setUpdateTime(LocalDateTime.now());
        setmealDto.setUpdateUser(id);

        setmealService.update(setmealDto);
        return R.success("编辑成功");
    }

    @DeleteMapping("/deletes/{ids}")
    public R<String> deletes(@PathVariable List<Integer> ids){

        setmealService.deletes(ids);

        return R.success("操作成功");
    }
}
